Skip to main content

credentials 옵션

작성일 : 2024.12.23

credentials 옵션은 fetch 요청 시 쿠키, HTTP 인증, 클라이언트 SSL 인증서와 같은 자격 증명을 어떻게 처리할지 결정합니다.

각 옵션의 상세 설명:

1. credentials: 'omit'​

  • 쿠키를 절대 보내거나 받지 않습니다
  • 가장 제한적인 옵션입니다
  • 예: 완전히 공개된 API를 호출할 때 사용
fetch("https://api.example.com/data", {
  credentials: "omit", // 쿠키 없이 요청
});

2. credentials: 'same-origin'​

  • 같은 출처(도메인)로 요청할 때만 쿠키를 보냅니다
  • 기본값입니다
  • 예: 현재 웹사이트의 API를 호출할 때 사용
fetch("/api/user", {
  credentials: "same-origin", // 같은 도메인 요청에만 쿠키 포함
});

3. credentials: 'include'​

  • 모든 요청에 쿠키를 포함합니다
  • 크로스 오리진(다른 도메인) 요청에도 쿠키를 보냅니다
  • CORS가 필요하며, 서버에서 Access-Control-Allow-Credentials: true 헤더를 보내야 합니다
  • 예: 다른 도메인의 인증이 필요한 API를 호출할 때 사용
fetch("https://api.another-site.com/user", {
  credentials: "include", // 다른 도메인 요청에도 쿠키 포함
});

실제 사용 예시:

// 로그인 API 호출 (같은 도메인)
const login = async (email: string, password: string) => {
  const response = await fetch("/api/login", {
    method: "POST",
    credentials: "same-origin", // 같은 도메인이므로 same-origin 사용
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ email, password }),
  });
};

// 외부 API 호출 (다른 도메인)
const fetchExternalData = async () => {
  const response = await fetch("https://external-api.com/data", {
    credentials: "include", // 외부 API라서 include 사용
    headers: {
      "Content-Type": "application/json",
    },
  });
};

// 공개 API 호출 (인증 불필요)
const fetchPublicData = async () => {
  const response = await fetch("https://public-api.com/data", {
    credentials: "omit", // 인증이 필요없으므로 omit 사용
  });
};